import {Component, OnInit} from '@angular/core';
import {ApesMessageService} from '@shared/apes/message';
import {ApiService} from '@core/services/http/api.service';
import F2 from '@antv/f2';
import {TitleService} from '@core/services/title/title.service';
import * as CryptoJS from 'crypto-js';
import {ActivatedRoute, Params, Router} from '@angular/router';
import {deepClone} from '../../../utils/utils';

@Component({
  selector: 'phone-page',
  templateUrl: './phone-page.component.html',
  styleUrls: ['./phone-page.component.scss'],
})
export class PhonePageComponent implements OnInit {
  chart: any;
  tabData: any[];
  titleList = {};
  nowdate: any;
  yesterday: any;
  width: number = window.screen.availWidth - 30;
  selectedValue: string = '1001';

  complay = [
    {id: '1001', name: '广州', disabled: false},
    // {id: '2001', name: '湘潭', disabled: false},
    // {id: '2002', name: '兴义', disabled: false},
    // {id: '5001', name: '赋能店', disabled: false},
    // {id: '5013', name: '如约', disabled: false},
    // {id: '5015', name: '车大夫', disabled: false},
    // {id: 'GSID_ALL', name: '全国', disabled: false},
  ];

  constructor(private apiService: ApiService,
              private msg: ApesMessageService,
              private title: TitleService,
              private routeInfo: ActivatedRoute,
              private router: Router) {
  }

  ngOnInit() {
    this.title.setTitle('实时数据');
    // 获取当天日期
    this.nowdate = new Date();
    this.nowdate = this.nowdate.toISOString().slice(0, 10);
    this.yesterday = new Date(new Date().getTime() - (6 * 24 * 60 * 60 * 1000)).toISOString().slice(0, 10);

    this.routeInfo.queryParams.subscribe((params: Params) => {
      if (params && params.hasOwnProperty('value')) {
        let value = CryptoJS.enc.Base64.parse(params['value']);
        if (value) {
          this.selectedValue = value.toString(CryptoJS.enc.Utf8);
        }
      }
      let data = deepClone(this.complay);
      this.complay = data.map(item => {
        if (this.selectedValue !== '1001' && this.selectedValue !== item['id']) {
          return {...item, disabled: true};
        } else {
          return {...item, disabled: false};
        }
      });
    });


    this.getTableData();
    this.tabData = this.setTabData();
    this.getWeekData();

  }

  ngAfterViewInit() {
    // this.getLine();
  }

  toChildLeaderboard($event) {
    //  点击当前数据信息
    let data = $event;
    let value = CryptoJS.enc.Utf8.parse(JSON.stringify(data));
    value = CryptoJS.enc.Base64.stringify(value);
    //  当前选择公司
    let key = CryptoJS.enc.Utf8.parse(JSON.stringify(this.selectedValue));
    key = CryptoJS.enc.Base64.stringify(key);
    this.router.navigate(['/analysis/phonePage/leaderboard'], {queryParams: {key: key, value: value}});
  }

  change() {
    this.tabData = [];
    this.titleList = {};
    this.getTableData();
    this.tabData = this.setTabData();
    this.getWeekData();
  }

  // 获取当天数据
  getTableData() {
    let data = {'interfaceMethod': 'ipmXsrbService.getMdSaleRel', 'pdata': {'GSID': this.selectedValue}};
    this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            this.titleList = data;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  setTabData() {
    return [
      {
        titleList: [
          {handname: '服务业绩', feild: 'FWXSJE'},
          {handname: '保险业绩', feild: 'CXQRJE'},
          {handname: '七天销售业绩', feild: 'AVGMD'},
          {handname: '洗美', feild: 'XCMRJE'},
          // {handname: '洗车', feild: 'XCJE'},
          // {handname: '美容', feild: 'MRJE'},
          {handname: '保养', feild: 'BYJE'},
          {handname: '维修', feild: 'WXJE'},
          {handname: '钣喷', feild: 'BPJE'},
          {handname: '轮胎', feild: 'LTJE'},
          {handname: '改装', feild: 'GZJE'},
          // {handname: '年卡', feild: 'NKXSJE'},
          // {handname: '蓄电池', feild: 'XDCJE'},
        ],
        headList: [
          {handname: '服务业绩', feild: 'FWXSJE'},
          {handname: '保险业绩', feild: 'CXQRJE'},
        ],
        footerList: [
          {handname: '车流/台', feild: 'CLJDTC'},
          {handname: '年卡', feild: 'NKXSJE'},
          {handname: '定损', feild: 'DSJE'},
        ],
      },
    ];
  }

  // 获取7天数据
  getWeekData() {
    let data = {
      'interfaceMethod': 'ipmXsybForService.getXsyjList', 'pdata':
        {'YXQQ': this.yesterday, 'YXQZ': this.nowdate, 'CXLX': '2', 'GSID': this.selectedValue},
    };
    this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let item = JSON.parse(result.obj);
            item = item.sort(this.sortarr);
            for (let list of item) {
              list['TJRQ'] = list['TJRQ'].slice(5, 10);
              list['TJRQ'] = list['TJRQ'].replace('-', '/');
            }
            this.getLine(item, 'TJRQ', 'FWXSJE');
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 汇折线图
  getLine(data: any[], x: string, y: any) {
    // @ts-ignore
    const chart = new F2.Chart({
      id: 'mountNode',
      width: this.width,
    });

    chart.source(data, {
      FWXSJE: {
        tickCount: 5,
        min: 0,
      },
      TJRQ: {
        range: [0, 1],
        tickCount: 4,
      },
    });
    chart.tooltip({
      showCrosshairs: true,
      showItemMarker: false,
      onShow: function onShow(ev) {
        let items = ev.items;
        for (let list of data) {
          if (list.FWXSJE == items[0].value) {
            items[0].name = list.TJRQ;
            items[0].value = '¥ ' + Math.round(items[0].value);
            return;
          }
        }
      },
    });
    chart.axis(x, {
      label: function label(text, index, total) {
        let textCfg = {};
        if (index === 0) {
          textCfg['textAlign'] = 'left';
        } else if (index === total - 1) {
          textCfg['textAlign'] = 'right';
        }
        return textCfg;
      },
    });
    chart.line().position(x + '*' + y);
    chart.point().position(x + '*' + y).style({
      stroke: '#fff',
      lineWidth: 1,
    });
    chart.render();
  }

  // 排序 升序
  sortarr(a, b) {
      return Date.parse(a['TJRQ']) - Date.parse(b['TJRQ']);
  }
}
